import React, { useState, useEffect } from "react";
import { Tree, message, Button } from "antd";
import {
  permitsList,
} from "@/api/permits";
import './roles.less'

function PermitsList(props) {
  const [treeData, setTreeData] = useState([])
  const [checkedKeys, setCheckedKeys] = useState([])

  const getPermitsData = () => {
    permitsList()
      .then((res) => {
        if (res.data.code === 200) {
          const data = res.data
          let list = data.data
          list = formatPermits(list)
          console.log('list', list)
          setTreeData(list)
        } else {
          message.error(res.data.msg);
        }
      })
  }

  const formatPermits = list => {
    for (let i = 0; i < list.length; i++) {
      if (list[i].children && list[i].children.length) {
        formatPermits(list[i].children)
      }
      list[i].title = list[i].name
      list[i].key = list[i].id.toString()
    }
    return list
  }

  const updateChildren = authIds => {
    if (authIds) {
      setCheckedKeys(authIds.split(','))
    } else {
      setCheckedKeys([])
    }
  }

  const onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };

  const onCheck = (checkedKeys, info) => {
    setCheckedKeys(checkedKeys)
  };

  const onCancel = () => {
    props.onCancel();
  };

  const onOk = () => {
    const authIds = checkedKeys.join(",");
    props.onOk(authIds);
  }

  useEffect(() => {
    getPermitsData();
    updateChildren(props.authIds);
  }, [])// eslint-disable-line react-hooks/exhaustive-deps

  return (
    <div>
      <Tree
        checkable
        onSelect={onSelect}
        onCheck={onCheck}
        treeData={treeData}
        checkedKeys={checkedKeys}
      />
      <div className="permitListBottom">
        <Button type='primary' onClick={onOk}>
          配置
        </Button>
        <Button onClick={onCancel} className='cancelBtn'>
          取消
        </Button>
      </div>
    </div>
  );
}

export default PermitsList;
